import { Injectable } from '@angular/core';

import {
    ActivatedRouteSnapshot, CanActivate,
    CanActivateChild,
    CanLoad, Route,
    Router,
    RouterStateSnapshot
} from '@angular/router';

import { AuthenticationService } from '../services/authentication.service';

@Injectable()
export class AuthenticationGuardService implements CanActivate, CanActivateChild, CanLoad {
    // isAuthenticated: boolean = false;

    constructor(
        private authenticationService: AuthenticationService,
        private router: Router
    ) {
        // this.authenticationService.isAuthenticated.subscribe(p => this.isAuthenticated = p);
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let url: string = state.url;

        return this.checkLogin(url);
    }

    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        // return this.canActivate(route, state);

        return false;
    }

    // CanLoad blocks preload
    // The PreloadAllModules strategy does not load feature areas protected by a CanLoad guard. 
    // This is by design.
    // If you want to preload a module and guard against unauthorized access, drop the canLoad() 
    // guard method and rely on the canActivate() guard alone.
    canLoad(route: Route): boolean {
        let url = `/${route.path}`;
        return this.checkLogin(url);
    }

    checkLogin(url: string): boolean {
        this.authenticationService.checkSessionDataExisting();

        if (this.authenticationService.currentAuthenticationState) {
            return true;
        }

        // Stores the attempted URL for redirecting.
        this.authenticationService.redirectUrl = url;

        // Creates a dummy session id
        let sessionId = 123456789;

        // Sets our navigation extras object if needed.
        // that contains our global query params and fragment.
        // let navigationExtras: NavigationExtras = {
        //     queryParams: { 'session_id': sessionId },
        //     fragment: 'anchor'
        // };

        // Navigate to the login page with extras.
        // Example: /authentication/login?session_id=123456789#anchor
        // this.router.navigate(['/authentication/login'], navigationExtras);
        this.router.navigate(['/authentication/login']);
        return false;
    }
}